package com.liang.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.liang.springcloud.dao.PaymentDao;
import com.liang.springcloud.entities.Payment;
import com.liang.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.naming.Name;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private PaymentDao paymentDao;

    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }

    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }

    @Override
    public String payment_ok(Integer id) {
        return "线程池"+Thread.currentThread().getName()+"payment_ok,id:"+id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "payment_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    public String payment_timeOut(Integer id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "线程池"+Thread.currentThread().getName()+"payment_timeOut,id:"+id;
    }

    /**
     * 兜底方案，超时时调用
     * @return
     */
    private String payment_TimeOutHandler(Integer id){
        return "线程池:" + Thread.currentThread().getName() + "payment服务 系统繁忙或运行错误,请稍后重试,id:"  + "\t" + "o(╥﹏╥)o";
    }

    //============服务熔断

    /**
     * 在窗口期内，请求10次，如果有60%请求失败(负数)调用fallbackMethod后，就会跳闸，一会后就会恢复正常
     * 过程：服务降级-服务熔断-恢复调用链路
     * @param id
     * @return
     */
    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 10){
            throw new RuntimeException("*******id不等为负数********");
        }
        String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"调用成功--serial:"+uuid;
    }
    private String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "ID不能为负数";
    }


}
